package com.tdcy.rest.sys;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import sun.misc.BASE64Decoder;

import com.tdcy.framework.BaseController;
import com.tdcy.framework.exception.QuickuException;
import com.tdcy.framework.util.RestUtils;
import com.tdcy.framework.util.StringUtils;
import com.tdcy.framework.util.WebUtils;
import com.tdcy.sys.dao.eo.FileFileEO;
import com.tdcy.sys.service.IFileSvc;

@Controller
@RequestMapping(value = "/upload")
public class ImageController extends BaseController {

	@Resource
	IFileSvc filesvc;

	/**
	 * upload
	 * 
	 * @param response
	 * @param request
	 * @param file
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "/uploadImageBase64", method = RequestMethod.POST)
	public Object uploadImageBase64(HttpServletResponse response, HttpServletRequest request) throws IOException {
		Map<String, String> param = RestUtils.getRestParam(request); 
		String imgBase64Str = StringUtils.getString(param, "imgBase64Str");
		if (StringUtils.isEmpty(imgBase64Str)) {
			throw new QuickuException("-1", "imgBase64Str不能为空");
		}

		String contentType = StringUtils.getString(param, "contentType");
		if (StringUtils.isEmpty(contentType)) {
			throw new QuickuException("-2", "contentType不能为空");
		}

		String fileName = StringUtils.getString(param, "fileName");
		if (StringUtils.isEmpty(fileName)) {
			throw new QuickuException("-3", "fileName不能为空");
		}

		BASE64Decoder decoder = new BASE64Decoder();
		// Base64解码
		byte[] b = decoder.decodeBuffer(imgBase64Str);
		for (int i = 0; i < b.length; ++i) {
			if (b[i] < 0) {// 调整异常数据
				b[i] += 256;
			}
		}

		FileFileEO eo = filesvc.addFileFile(fileName, contentType, b);
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("fileid", eo.getId());

		return WebUtils.createJSONSuccess("上传成功", m);
	}

	/**
	 * upload
	 * 
	 * @param response
	 * @param request
	 * @param file
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "/disposeFile", method = RequestMethod.POST)
	public Object disposeFile(HttpServletResponse response, HttpServletRequest request) throws IOException {
		Map<String, String> param = RestUtils.getRestParam(request); 
		String fileid = StringUtils.getString(param, "fileid");
		if (StringUtils.isEmpty(fileid)) {
			throw new QuickuException("-1", "fileid不能为空");
		}
		filesvc.delFileFile(Integer.parseInt(fileid),false);
		Map<String, Object> m = new HashMap<String, Object>();

		return WebUtils.createJSONSuccess("删除成功", m);
	}
}
